package com.coffee.web.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.coffee.admin.api.common.service.RedisService;
import com.coffee.core.anotation.LoginCheck;
import com.coffee.core.entity.SiteContextThreadLocal;
import com.coffee.core.util.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    private static final Logger LOG = LoggerFactory.getLogger(LoginCheckInterceptor.class);

    @Value("${parameter.webDomain}")
    private String webDomain;

    @Reference(check = false)
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws IOException {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 登录状态校验
        LoginCheck loginCheck = handlerMethod.getMethodAnnotation(LoginCheck.class);
        if (loginCheck == null) {
            // 不需要校验登录状态
            return true;
        }

        boolean isLogin = isLogin();

        if (!isLogin) {
            if (WebUtil.isAjaxRequest(request, response, handlerMethod)) {
                response.setContentType("application/json;charset=UTF-8");

                Map<String, Object> data = notLoginRes();
                response.getWriter().write(JSONObject.toJSONString(data));
            } else {
                String loginPageUrl = webDomain + "/v1/login";
                response.sendRedirect(loginPageUrl);
            }

            return false;
        }
        return true;
    }


    private boolean isLogin() {
        String token = SiteContextThreadLocal.get().getCtoken();

        if (StringUtils.isEmpty(token)) {
            return false;
        }


        boolean hasKey = redisService.hasKey(token);
        if (!hasKey) {
            return false;
        }

        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) {
    }


    private Map<String, Object> notLoginRes() {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("isLogin", false);
        data.put("code", "unLogin");
        data.put("message", "您还尚未登录");
        return data;
    }
}
